/**
 * 食药公用js
 *
 * */
define([
    'base',
    'msgTool',
    'bootstrapDialog',
    'laydate',
    'bootstrapTable',
    'highcharts',
    'exporting',
    'highchartsCN',
    'sandSignika',
    'jqViewer',
    'jqPrint',
    'css!global/plugins/wangEditor/wangEditor.min.css',
    'plugins/wangEditor/wangEditor.min',
    'css!global/plugins/viewer/viewer.min.css',
    'plugins/fileInput/fileinput.min',
    'css!global/plugins/fileInput/fileinput.min.css',
], function (base, msgTool, BootstrapDialog, laydate, _, highcharts, _, _, _, _, jqPrint, _, E) {
    //默认加载基础库
    base();
    return {
        list: function (webUrl) {
        	
            $.post('cateSelect.json', {},
                    function (data) {
                        if (data.success) {
                            var selectHtml = "<option value=''>请选择</option>";
                            $.each(data.rows, function (i, itemCate) {
                                selectHtml += "<option value='" + itemCate.id + "'  >" + itemCate.title + "</option>";
                            });
                            $("#cateSearch").html(selectHtml);
                        }
                    }, "json");

            var selectHtml = "<option value=''>请选择</option>";
            $("#mainSearch").html(selectHtml);             
              

                $("#cateSearch").change(function () {
                    var param = $("#cateSearch option:selected").val();
                    if (param == '') {
                        $("#mainSearch").html("<option value=''>请选择</option>");
                    } else {
                        $.post('mainItemSelect.json', {'cateId': param},
                            function (data) {
                                if (data.success) {
                                    var selectHtml = "<option value=''>请选择</option>";
                                    $.each(data.rows, function (i, itemMain) {
                                        selectHtml += "<option value='" + itemMain.id + "'>" + itemMain.title + "</option>";
                                    });
                                    $("#mainSearch").html(selectHtml);
                                }
                            }, "json");
                    }

                });
                
                
            var myTable = $('#dataList');
            var tableRefresh = function () {
                myTable.bootstrapTable('refresh', {url: 'list.json'})
            };
            //table按需刷新动作
            var doAction = function (obj) {
                myTable.bootstrapTable('refresh', {url: 'list.json?pid=' + obj.id})
            };

            //table当前行的响应事件
            window.operateEvents = {
                'click .update': function (e, value, row) {
                    window.location.href = row.id;
                },
                'click .status': function (e, value, row) {
                    $.baseUtils.oneStatus({
                        row: row,
                        tableName: myTable,
                        nameText: '办件事项',
                        nameValue: row.title,
                        url: '../status/action'
                    })
                },
                'click .delete': function (e, value, row) {
                    $.baseUtils.oneDelete({
                        row: row,
                        tableName: myTable,
                        nameText: '办件事项',
                        nameValue: row.title,
                        url: '../delete/action'
                    });
                }
            };


            //table表格
            myTable.bootstrapTable({
                url: 'list.json', // 接口 URL 地址
                cache: false, // 不缓存
                striped: true, // 隔行加亮
                pagination: true, // 开启分页功能
                sidePagination: 'server',//服务端分页
                sortOrder: 'desc', // 设置排序为反序 desc
                fixedColumns: true,//自动修复
                queryParams: queryParams,//搜索附加参数
                smartDisplay: false, // 智能显示 pagination 和 cardview 等
                toolbar: ".toolBar", //顶部工具菜单
                toolbarAlign: "right", //顶部工具位置
                mobileResponsive: "true", //手机模式自适应宽度（自动变成卡片模式）
                columns: [
                    {
                        field: 'id',
                        title: '事项编号',
                        align: 'center',
                        width: '5%'
                    }, {
                        field: 'title',
                        title: '办件事项名称',
                        width: '15%',
                        formatter: function (value, row, index) {
                            return '<i class="fa fa-hashtag text-primary" aria-hidden="true"></i>&emsp;<b>' + value
                        }
                    },
                    {
                        field: 'matterNature',
                        title: '事项性质',
                        align: 'center',
                        width: '5%',
                        formatter: function (value, row, index) {
                        	  var result = "<i class=\"fa fa-signal\" aria-hidden=\"true\"></i>&nbsp;未知";
                              switch (value) {
                                  case 1:
                                      result = "<i class=\"fa fa-signal\" aria-hidden=\"false\"></i>&nbsp;公示";
                                      break;
                                  case 2:
                                      result = "<i class=\"fa fa-signal\" aria-hidden=\"true\"></i>&nbsp;申报";
                                      break;
                                  default:
                                      break;
                              }
                            return result;
                        }
                    }, {
                        field: 'link',
                        title: '事项链接',
                        width: '20%',
                        formatter: function (value, row, index) {
                            if (value === null || value === '') {
                                return "-";
                            }
                            return '<i class="fa fa-link" aria-hidden="true"></i>&emsp;<a href="' + webUrl + value + '" target="_blank">' + value + '</a>';
                        }
                    }, {
                        field: 'cateTitle',
                        title: '事项类型',
                        align: 'center',
                        width: '10%'
                    }, {
                        field: 'legalTerm',
                        title: '法定期限',
                        width: '10%',
                        formatter: function (value, row, index) {
                            return '<i class="fa fa-clock-o" aria-hidden="true"></i>&nbsp;' + value + '个工作日'
                        }
                    },
                    {
                        field: 'promiseTerm',
                        title: '承诺期限',
                        width: '10%',
                        formatter: function (value, row, index) {
                            return '<i class="fa fa-clock-o" aria-hidden="true"></i>&nbsp;' + value + '个工作日'
                        }
                    },  {
                        field: 'sort',
                        title: '排序',
                        width: '5%',
                        align:'center'
                    },{
                        field: 'status',
                        title: '状态',
                        width: '10%',
                        align: 'center',
                        formatter: function (value, row, index) {
                            var result = "";
                            switch (value) {
                                case 0:
                                    result = "<span class=\"label label-danger\"><i class=\"fa fa-lock\" aria-hidden=\"false\"></i>&nbsp;禁用</span";
                                    break;
                                case 1:
                                    result = "<span class=\"label label-primary\"><i class=\"fa fa-unlock\" aria-hidden=\"true\"></i>&nbsp;启用</span";
                                    break;
                                default:
                                    break;
                            }
                            return result;
                        }
                    }, {
                        field: 'action',
                        title: '操作',
                        align: 'center',
                        width: '10%',
                        formatter: operateFormatter,
                        events: operateEvents
                    }
                ]
            });

            //搜索刷新
            $('#search-btn').on('click', function () {
                tableRefresh();
            });


            //刷新
            $(".toolbar-refresh").on('click', function () {
                tableRefresh();
            });

            //批量修改状态
            $(".toolbar-batchStatus").on('click', function () {
                var entityList = myTable.bootstrapTable('getSelections');
                var row = [], names = [];
                $.each(entityList, function (i, v) {
                    names.push(v.itemName);
                    row.push(v.id);
                });
                if (row.length > 0) {
                    $.baseUtils.batchAction({
                        row: row,
                        tableName: myTable,
                        nameText: '食药申请',
                        nameValue: names,
                        url: '../status/batchAction'
                    });
                } else {
                    msgTool.error("请选择虽少一条记录后再操作", "信息提示");
                }

            });


            //搜索参数传递
            function queryParams(params) {
                params.search = $("#search").val();
                params.cateSearch = $("#cateSearch").val();
                params.mainSearch = $("#mainSearch").val();
                return {
                    limit: params.limit,
                    offset: params.offset,
                    cateId: params.cateSearch,
                    mainId:params.mainSearch,
                    search: params.search//标题模糊搜
                };
            }

            //回显
            function responseHandler(res) {
                return res.rows;
            }

        },
        view: function () {


        },

        save: function (cateId,mainId) {
        	  	       
        	$("#picture").mouseover(function(e){
        		var imgUrl=$("#pictureVal").val();
        		var x,y; 
        		x = e.clientX-200+'px'; 
        		y = e.clientY-150+'px'; 
        		$("#layer").css('left',x); 
        		$("#layer").css('top', y); 
        		$("#layer").html("<img  style='width: 200px;height: 200px;' src='http://127.0.0.1:8081/"+imgUrl+"'>");
        		$("#layer").css("display","");
        	});

        	$("#picture").mouseout(function(){
        		$("#layer").html("");
        		$("#layer").css('display','none'); 
        	});

            //工作时间
            laydate.render({
                elem: '#officeTime',
                type: 'time',
                format: 'H:mm',
                value:'9:00 - 17:30',
                range: true
            });

            $.post('cateSelect.json', {},
                function (data) {
                    if (data.success) {
                        var selectHtml = "<option value=''>请选择</option>";
                        $.each(data.rows, function (i, itemCate) {
                        	var flag="";
                        	if(cateId==itemCate.id){
                        		flag="selected";
                        	}
                            selectHtml += "<option value='" + itemCate.id + "'  "+flag+" >" + itemCate.title + "</option>";
                        });
                        $("#cateId").html(selectHtml);
                    }
                }, "json");

            $.post('mainItemSelect.json', {'cateId': cateId},
                    function (data) {
                        if (data.success) {
                            var selectHtml = "<option value=''>请选择</option>";
                            $.each(data.rows, function (i, itemMain) {
                            	var flag="";
                            	if(mainId==itemMain.id){
                            		flag="selected";
                            	}
                                selectHtml += "<option value='" + itemMain.id + "'  "+flag+"   >" + itemMain.title + "</option>";
                            });
                            $("#mainId").html(selectHtml);
                        }
                    }, "json");

            $("#cateId").change(function () {
                var param = $("#cateId option:selected").val();
                if (param == '') {
                    $("#mainId").html("<option value=''>请选择</option>");
                } else {
                    $.post('mainItemSelect.json', {'cateId': param},
                        function (data) {
                            if (data.success) {
                                var selectHtml = "<option value=''>请选择</option>";
                                $.each(data.rows, function (i, itemMain) {
                                    selectHtml += "<option value='" + itemMain.id + "'>" + itemMain.title + "</option>";
                                });
                                $("#mainId").html(selectHtml);
                            }
                        }, "json");
                }

            });
            
            
    	    //二寸照片
    	    oneUploader("#pictureUploader", "请上传app图标" , "#userPhoto-upload-error", "#userPhoto-upload-success", "userPhoto");
    	   
    		
    	    
    	    function oneUploader(node, placeholder, elErrorContainer, successContainer, name) {
    	        return $(node).fileinput({
    	            //设置语言
    	            language: 'zh',
    	            //上传的地址
    	            uploadUrl: '/common/uploader/index',
    	            //上传方式
    	            method: 'post',
    	            //文件筐信息
    	            msgPlaceholder: placeholder,
    	            //附加属性(0图片，1文件)
    	            uploadExtraData: {filesType: 0},
    	            //上传类型
    	            allowedFileExtensions: ['jpg', 'gif', 'png', 'jpeg'],
    	            //是否显示图片展示框
    	            showPreview: false,
    	            //是否显示上传按钮
    	            showUpload: true,
    	            //是否显示取消按钮
    	            showCancel: false,
    	            //是否显示上传输入框
    	            showCaption: true,
    	            //是否显示删除键
    	            showRemove: false,
    	            //浏览图标
    	            browseIcon: '<i class="iconfont icon-wenjianjia"></i>&nbsp;',
    	            //浏览样式
    	            browseClass: 'btn btn-success btn-outline',
    	            //上传图标
    	            uploadIcon: '<i class="iconfont icon-upload"></i>&nbsp;',
    	            //上传样式
    	            uploadClass: 'btn btn-success btn-outline',
    	            //单位为kb，(30M)如果为0表示不限制文件大小
    	            maxFileSize: 10720,
    	            //错误显示位置
    	            elErrorContainer: elErrorContainer,
    	            //错误显示位置节点样式
    	            msgErrorClass: 'alert alert-block alert-danger',
    	            //验证数量
    	            validateInitialCount: true
    	        }).on("fileuploaded", function (event, data) {
    	        	   if (data.response !== null && data.response.status) {
    	           		   $("#pictureVal").val(data.response.domain + data.response.url );
    	        	   } else {
    	                   $(elErrorContainer).text(data.response.message);
    	               }
    	        });
    	    }
            

            /**
             * 富文本编辑器
             *
             */
            createEditor("#guideEditer", "textarea[name='guide']");
            createEditor("#costEditer", "textarea[name='cost']");
            createEditor("#materialEditer", "textarea[name='material']");
            $("#itemForm").validate({
                rules: {
                    title: {
                        required: true
                    },
                    matterNature: {
                        required: true
                    },
                    cateId: {
                        required: true
                    },
                    legalTerm: {
                        required: true
                    },
                    promiseTerm: {
                        required: true
                    },
                    approvalUnit: {
                        required: true
                    },
                    address: {
                        required: true
                    },
                    phone: {
                        required: true
                    },
                    officeTime: {
                        required: true
                    },
                    link: {
                        required: true
                    },
                    sort: {
                        required: true
                    }
                },
                messages: { //自定义验证消息
                    title: {
                        required: "请输入事项名称"
                    },
                    matterNature: {
                        required: "请输入事项性质"
                    },
                    cateId: {
                        required: "请输入事项分类"
                    },
                    legalTerm: {
                        required: "请输入法定时限"
                    },
                    promiseTerm: {
                        required: "请输入承诺期限"
                    },
                    approvalUnit: {
                        required: "请输入审批主体"
                    },
                    address: {
                        required: "请输入办公地址"
                    },
                    phone: {
                        required: "请输入联系电话"
                    },
                    officeTime: {
                        required: "请输入办公时间"
                    },
                    link: {
                        required: "请输入事项链接"
                    },
                    sort: {
                        required: "请输入事项排序"
                    }
                }
            });

            //保存
            $('#doSubmit').on('click', function () {
            	var  matterNature=$("#matterNature").val();
            	  var valid =true;
            	if(matterNature==2){
            		var valid = $("#itemForm").validate().form();
            	}
                if (valid) {
                    $.ajax({
                        url: '../save/action',
                        type: 'POST',
                        data: $('#itemForm').serialize(),
                        dataType: "JSON",
                        success: function (data) {
                            if (data.success) {
                                msgTool.success("保存成功！");
                            } else {
                                msgTool.error("保存失败！");
                            }
                        },
                        error: function (error) {
                            msgTool.error("操作失败，请刷新当前页面后重试！");
                        }
                    });
                }
            });

            function createEditor(editor, deails) {
                var editor = new E(editor);
                var deails = $(deails);
                // 监控变化，同步更新到 textarea
                editor.customConfig.onchange = function (html) {
                    deails.text(html);
                };
                // 配置服务器端地址
                editor.customConfig.uploadImgServer = '/common/uploader/index';
                // 将图片大小限制为 30M
                editor.customConfig.uploadImgMaxSize = 30 * 1024 * 1024;
                // 限制一次最多上传 5 张图片
                editor.customConfig.uploadImgMaxLength = 50;
                // 上传文件名，类似于input>type=file>name
                editor.customConfig.uploadFileName = 'files';
                // 将 timeout 时间改为 20s
                editor.customConfig.uploadImgTimeout = 20000;
                // 自定义上传参数
                editor.customConfig.uploadImgParams = {
                    filesType: 2
                };
                editor.create();

            }

        }
    }
});






